﻿using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

public class FurRenderFeature : ScriptableRendererFeature
{
    [Range(1, 40)] public int layerNum = 20;
    public RenderPassEvent renderPassEvent = RenderPassEvent.AfterRenderingTransparents;

    FurRenderPass m_ScriptablePass;

    public override void Create()
    {
        m_ScriptablePass = new FurRenderPass(layerNum)
        {
            renderPassEvent = renderPassEvent
        };
    }

    public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
    {
        renderer.EnqueuePass(m_ScriptablePass);
    }
    
    // ------ FurRenderPass ------
    class FurRenderPass : ScriptableRenderPass
    {
        FilteringSettings m_Filter;
        readonly int m_LayerNum;

        public FurRenderPass(int layerNum)
        {
            m_LayerNum = layerNum;
            m_Filter = new FilteringSettings(new RenderQueueRange(2000, 5000));
        }

        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            CommandBuffer cmd = CommandBufferPool.Get("--- FUR ---");

            var drawingSetting = CreateDrawingSettings(new ShaderTagId("FurRenderer"), ref renderingData, SortingCriteria.CommonOpaque);
            var layerDrawingSetting = CreateDrawingSettings(new ShaderTagId("FurRendererTransparent"), ref renderingData, SortingCriteria.CommonTransparent);

            cmd.SetGlobalFloat("_FurOffset", 0);
            var inter = 1.0f / m_LayerNum;

            context.ExecuteCommandBuffer(cmd);
            context.DrawRenderers(renderingData.cullResults, ref drawingSetting, ref m_Filter);

            // 循环绘制
            for (var i = 1; i < m_LayerNum; i++)
            {
                cmd.Clear();
                cmd.SetGlobalFloat("_FurOffset", i * inter);
                context.ExecuteCommandBuffer(cmd);
                context.DrawRenderers(renderingData.cullResults, ref layerDrawingSetting, ref m_Filter);
            }

            CommandBufferPool.Release(cmd);
            cmd.Clear();
        }
    }
}